package com.kun.kunnmall.secikll.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kun.common.to.SeckillOrderTo;
import com.kun.common.utils.R;
import com.kun.kunnmall.secikll.feign.CouponFeignService;
import com.kun.kunnmall.secikll.feign.ProductFeignService;
import com.kun.kunnmall.secikll.interceptor.SeckillLoginUserInterceptor;
import com.kun.kunnmall.secikll.service.SeckillService;
import com.kun.kunnmall.secikll.to.SeckillSkuRedisTo;
import com.kun.kunnmall.secikll.vo.SeckillSessionWithSkus;
import com.kun.kunnmall.secikll.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.model.ITemplateEnd;


import java.util.*;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_SKU_PREFIX = "seckill:skus";

    private final String SKU_SECKILL_STOCK_SEMAPHORE = "seckill:stock:"; // 后面接的是商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.去数据库扫描哪些商品参与秒杀
        R r = couponFeignService.getLatest3DaysSession();
        if (r.getCode() == 0) {
            // 远程调用成功
            List<SeckillSessionWithSkus> data = r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            // 2. 将需要上架的商品缓存到redis当中(key是最近几天活动的开始和结束时间，value是活动所关联的商品id，商品的详细信息在做一个缓存)
            saveSessionInfos(data);
            saveSessionSkuInfos(data);
        }
    }

    /**
     * 保存活动信息
     *
     * @param data
     */
    private void saveSessionInfos(List<SeckillSessionWithSkus> data) {
        if (data != null) {
            data.forEach(item -> {

                long startTime = item.getStartTime().getTime();
                long endTime = item.getEndTime().getTime();
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;

                // 缓存秒杀活动信息
                // 判断是否已经缓存了
                Boolean hasKey = redisTemplate.hasKey(key);
                if (Boolean.FALSE.equals(hasKey)) {
                    List<String> skuIds = item.getRelationSkus().stream()
                            .map(seckillSkuVo -> seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString())
                            .collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, skuIds);
                }

            });
        }

    }

    /**
     * 保存活动所关联的商品的详细信息
     *
     * @param data
     */
    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> data) {
        if (data != null) {
            data.forEach(item -> {


                // 绑定一个hash操作
                BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);
                item.getRelationSkus().forEach(seckillSkuVo -> {
                    // 生成商品随机码
                    String randomCode = UUID.randomUUID().toString().replace("-", "");
                    // 判断是否已经缓存过了
                    if (Boolean.FALSE.equals(hashOps.hasKey(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString()))) {
                        // 缓存中没有
                        SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                        // 1. sku的基本信息
                        R r = productFeignService.info(seckillSkuVo.getSkuId());
                        if (r.getCode() == 0) {
                            // 远程调用成功
                            SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            seckillSkuRedisTo.setSkuInfo(skuInfo);
                        }

                        // 2. sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, seckillSkuRedisTo);

                        // 3. sku秒杀的开始和结束时间
                        seckillSkuRedisTo.setStartTime(item.getStartTime().getTime());
                        seckillSkuRedisTo.setEndTime(item.getEndTime().getTime());

                        // 4. 商品的随机码
                        seckillSkuRedisTo.setRandomCode(randomCode);

                        // 5. 保存商品的秒杀信息和商品详细信息到redis
                        String jsonStr = JSONUtil.toJsonStr(seckillSkuRedisTo);
                        hashOps.put(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString(), jsonStr);

                        // 6. 设置每个商品的信号量（作用：限流）
                        // 如果当前场次的商品库存信息已经上架了，就不需要要上架了
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_SECKILL_STOCK_SEMAPHORE + randomCode);
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    }

                });

            });
        }
    }


    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 1. 确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        // 找到rerdis中所有活动场次的key
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");

        for (String key : keys) {

            // 根据key获取所有活动场次的开始和结束时间
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] split = replace.split("_");
            long startTime = Long.parseLong(split[0]);
            long endTime = Long.parseLong(split[1]);

            if (time >= startTime && time <= endTime) {
                // 找到了当前时间所在的秒杀场次
                // 2. 获取当前场次的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, Object> hashOps = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);
                List<Object> list = hashOps.multiGet(range);
                if (list != null) {
                    List<SeckillSkuRedisTo> collect = list.stream()
                            .map(item -> JSONUtil.toBean((String) item, SeckillSkuRedisTo.class))
                            .collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        // 获取秒杀商品
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSeckillInfo(Long skuId) {
        // 找到所有需要参与秒杀的商品的key信息
        BoundHashOperations<String, String, Object> ops = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);
        Set<String> keys = ops.keys();
        String regx = "\\d_" + skuId; // 需要匹配的key
        if (keys != null && keys.size() > 0) { // 判断有没有秒杀商品
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    // 找了该商品的秒杀信息
                    String str = (String) ops.get(key);
                    SeckillSkuRedisTo redisTo = JSONUtil.toBean(str, SeckillSkuRedisTo.class);
                    // 判断当前时间是否在秒杀时间区间内
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    long currentTime = new Date().getTime();
                    if (currentTime >= startTime && currentTime < endTime) {
                        // 当前时间在商品的秒杀时间
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    /**
     * 秒杀商品
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        // 1. 登录校验（拦截器已经做过了）
        // 1.1 从redis当中获取要秒杀的商品信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);
        String s = ops.get(killId);
        if (StrUtil.isNotEmpty(s)) {
            SeckillSkuRedisTo skuRedisTo = JSONUtil.toBean(s, SeckillSkuRedisTo.class);
            // 2. 合法性校验（校验所传参数的合法性）
            // 2.1 判断秒杀时间过没有过
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();

            long expireTime = endTime - startTime; // 该商品秒杀活动的过期时间

            long currentTime = new Date().getTime();
            if (currentTime >= startTime && currentTime <= endTime) {
                // 当前时间处在秒杀商品的秒杀时间内
                // 2.2 校验随机码和商品id是否正确
                String randomCode = skuRedisTo.getRandomCode();
                String redisKillId = skuRedisTo.getPromotionSessionId() + "_" + skuRedisTo.getSkuId();
                if (key.equals(randomCode) && killId.equals(redisKillId)) {
                    // 说明killId，和key是合法的
                    // 2.3 验证num是否正确
                    if (num <= skuRedisTo.getSeckillLimit()) {
                        // 2.4 校验购买资格。幂等性处理；只要秒杀成功，就去redis里面占一个位置
                        String userKey = SeckillLoginUserInterceptor.loginUser.get().getId() + "_" + redisKillId;
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(userKey, num.toString(), expireTime, TimeUnit.MILLISECONDS);
                        if (Boolean.TRUE.equals(ifAbsent)) {
                            // 占位成功，说明用户有购买资格
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_SECKILL_STOCK_SEMAPHORE + randomCode);
                            try {
                                // 尝试获取信号量（库存）
                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                if (b) {
                                    // 获取信号成功
                                    // 3. 快速下单，发送消息到rabbitmq。
                                    String orderSn = IdWorker.getTimeId();

                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderSn(orderSn);
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
                                    seckillOrderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                    seckillOrderTo.setMemberId(SeckillLoginUserInterceptor.loginUser.get().getId());
                                    seckillOrderTo.setSkuId(skuRedisTo.getSkuId());

                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);

                                    return orderSn;// 秒杀成功
                                }
                            } catch (InterruptedException e) {
                                return null;
                            }
                        }
                    }
                }
            }
        }

        return null;
    }
}
